package com.kchouse.homepage;

import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Paint;
import android.graphics.drawable.BitmapDrawable;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;

import com.alibaba.fastjson.JSONObject;
import com.amap.api.maps2d.AMapUtils;
import com.amap.api.maps2d.model.LatLng;
import com.gxz.PagerSlidingTabStrip;
import com.kchouse.ListFragment;
import com.kchouse.MainActivity;
import com.kchouse.R;
import com.kchouse.StartActivity;
import com.kchouse.UnionFragment;
import com.kchouse.bean.HostItem;
import com.kchouse.common.API;
import com.kchouse.common.BaseActivity;
import com.kchouse.common.BaseApp;
import com.kchouse.common.MyHttpCycleContext;
import com.kchouse.common.MyUtils;
import com.kchouse.common.ToastUtils;
import com.kchouse.mine.LoginPhoneActivity;
import com.kchouse.union.GDMapFragment;
import com.kchouse.view.QRCode;
import com.squareup.picasso.Picasso;
import com.tencent.mm.opensdk.modelmsg.SendMessageToWX;
import com.tencent.mm.opensdk.modelmsg.WXImageObject;
import com.tencent.mm.opensdk.modelmsg.WXMediaMessage;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.text.DecimalFormat;
import java.util.ArrayList;

import cn.finalteam.okhttpfinal.BaseHttpRequestCallback;
import cn.finalteam.okhttpfinal.HttpRequest;
import cn.finalteam.okhttpfinal.RequestParams;

import static cn.finalteam.toolsfinal.BitmapUtils.drawableToBitmap;

public class InsuranceActivity extends BaseActivity implements View.OnClickListener {

    private InsuranceActivity mContent;
    private TextView tv_title;
    private ImageView iv_back;
    private TextView tv_weixin;
    private View ll_lay1;
    private View ll_lay2;
    private Intent intent;
    private ListView lv_item;
    private ImageView iv_qcode;
    private Bitmap bp;
    private Button bt_item;
    private ArrayList<HostItem> listinsurance = new ArrayList<>();
    private LvAdapter adapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_insurance);

        mContent = this;
        intiData();
        intiView();
    }

    private void intiData() {
        intent = getIntent();

        GetInsuranceList();
    }

    /**
     * 获取用户保险套餐
     */
    private void GetInsuranceList() {
        String url = API.GetInsuranceList + MainActivity.userid;
        RequestParams params = new RequestParams(new MyHttpCycleContext());//请求参数
        params.addHeader("token", MainActivity.token);//添加header信息
//        params.addFormDataPart("pageSize", 10);

        HttpRequest.get(url, params, new BaseHttpRequestCallback<String>() {

            //请求网络前
            @Override
            public void onStart() {
                showdialog();
            }

            @Override
            protected void onSuccess(String str) {
                Log.e("==", str);
                JSONObject json = JSONObject.parseObject(str);
                if (json.getBoolean("successful")) {
                    String datastr = json.getString("data");
                    JSONObject data = JSONObject.parseObject(datastr);
                    listinsurance.addAll(JSONObject.parseArray(data.getString("insuranceList"), HostItem.class));

                    if (listinsurance.size() == 0) {
                        ll_lay1.setVisibility(View.VISIBLE);
                        ll_lay2.setVisibility(View.GONE);
                    } else {
                        ll_lay1.setVisibility(View.GONE);
                        ll_lay2.setVisibility(View.VISIBLE);
                    }
                    adapter.notifyDataSetChanged();
                } else {
                    String datastr = json.getString("data");
                    JSONObject data = JSONObject.parseObject(datastr);
                    if (data.getString("code").equals("401")||data.getString("code").equals("400")) {
                        intent.setClass(mContent, LoginPhoneActivity.class);
                        startActivity(intent);
                        finish();
                    } else {
                        ToastUtils.getInstanc(mContent).showToast(data.getString("msg"));
                    }
                }
            }

            //请求失败（服务返回非法JSON、服务器异常、网络异常）
            @Override
            public void onFailure(int errorCode, String msg) {
//                toast("网络异常~，请检查你的网络是否连接后再试");
                Log.e("==", msg);
            }

            //请求网络结束
            @Override
            public void onFinish() {
                dismissdialog();
            }
        });
    }


    private void intiView() {
        tv_title = (TextView) findViewById(R.id.tv_title);
        tv_title.setText("汽车保险");
        iv_back = (ImageView) findViewById(R.id.iv_back);
        iv_back.setOnClickListener(this);

        ll_lay1 = findViewById(R.id.ll_lay1);
        ll_lay2 = findViewById(R.id.ll_lay2);

        tv_weixin = (TextView) findViewById(R.id.tv_weixin);
        tv_weixin.setOnLongClickListener(new View.OnLongClickListener() {
            @Override
            public boolean onLongClick(View v) {
                ToastUtils.getInstanc(mContent).showToast("长按事件：复制" + tv_weixin.getText().toString());
                return false;
            }
        });


        lv_item = (ListView) findViewById(R.id.lv_item);
        adapter = new LvAdapter();
        lv_item.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                HostItem item = listinsurance.get(position);
                if (TextUtils.isEmpty(item.getMerchantId())) {
                    intent.putExtra("isDir", true);
                    intent.putExtra("id", item.getId());
                    intent.setClass(mContent, GoodsDetailsActivity.class);
                    startActivity(intent);
                } else {
                    intent.putExtra("isDir", false);
                    intent.putExtra("id", item.getId());
                    intent.setClass(mContent, GoodsDetailsActivity.class);
                    startActivity(intent);
                }
            }
        });
        lv_item.setAdapter(adapter);

        iv_qcode = (ImageView) findViewById(R.id.iv_qcode);
        Picasso.with(mContent).load("https://aawj.oss-cn-shenzhen.aliyuncs.com/20180916/ac5e7d3a96b74bdcb68f08f004eba8f6.jpg").error(R.mipmap.ic_loadingerror).into(iv_qcode);
//        try {
//            bp = returnBitMap("https://aawj.oss-cn-shenzhen.aliyuncs.com/20180916/ac5e7d3a96b74bdcb68f08f004eba8f6.jpg");
//        } catch (Exception e) {
//            e.printStackTrace();
//        }

        bt_item = (Button) findViewById(R.id.bt_item);
        bt_item.setOnClickListener(this);

    }


//    public Bitmap getImage(String path) throws Exception {
//        URL url = new URL(path);
//        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
//        InputStream is = conn.getInputStream();
//        return BitmapFactory.decodeStream(is);
//    }

//    /**
//     * 根据图片的url路径获得Bitmap对象
//     * @param url
//     * @return
//     */
//    private Bitmap returnBitmap(String url) {
//        URL fileUrl = null;
//        Bitmap bitmap = null;
//
//        try {
//            fileUrl = new URL(url);
//        } catch (MalformedURLException e) {
//            e.printStackTrace();
//        }
//
//        try {
//            HttpURLConnection conn = (HttpURLConnection) fileUrl
//                    .openConnection();
//            conn.setDoInput(true);
//            conn.connect();
//            InputStream is = conn.getInputStream();
//            bitmap = BitmapFactory.decodeStream(is);
//            is.close();
//        } catch (IOException e) {
//            e.printStackTrace();
//        }
//        return bitmap;
//    }




    class LvAdapter extends BaseAdapter {
        @Override
        public int getCount() {
            return listinsurance.size();
        }

        @Override
        public Object getItem(int position) {
            return null;
        }

        @Override
        public long getItemId(int position) {
            return 0;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {

//            View view = getLayoutInflater().inflate(R.layout.lv_insurance_item, null);
//
//            TextView tv_original = (TextView) view.findViewById(R.id.tv_original);
//            tv_original.getPaint().setFlags(Paint.STRIKE_THRU_TEXT_FLAG);//添加下划线

            HostItem item = listinsurance.get(position);
            View view = null;
            if (TextUtils.isEmpty(item.getMerchantId()))//是否联盟
            {
                view = getLayoutInflater().inflate(R.layout.lv_directly_item, null);
                TextView tv_pt = (TextView) view.findViewById(R.id.tv_pt);
                tv_pt.setVisibility(View.VISIBLE);
                TextView tv_original = (TextView) view.findViewById(R.id.tv_original);
                tv_original.setText(MyUtils.getdouble(item.getOriginalPrice()));
                tv_original.getPaint().setFlags(Paint.STRIKE_THRU_TEXT_FLAG);//添加下划线
                ImageView iv_item = (ImageView) view.findViewById(R.id.iv_item);
                Picasso.with(mContent).load(item.getUrl()).error(R.mipmap.ic_loadingerror).into(iv_item);
                TextView tv_price = (TextView) view.findViewById(R.id.tv_price);
                tv_price.setText(item.getPrice()+"");
//                tv_price.setText(MyUtils.getdouble(item.getPrice()));
                TextView tv_sales = (TextView) view.findViewById(R.id.tv_sales);
                tv_sales.setText("销量：" + item.getSales());
                TextView tv_title = (TextView) view.findViewById(R.id.tv_title);
                tv_title.setText(item.getName());
                TextView tv_giving = (TextView) view.findViewById(R.id.tv_giving);

                if (item.getCouponLimit() == 0) {
                    tv_giving.setText("");
                } else {
                    tv_giving.setText("最高抵扣" + (item.getCouponLimit() * 10) + "元");
                }

//                tv_giving.setText("最高抵扣" + (item.getCouponLimit() * 10) + "元");

            } else {
                view = getLayoutInflater().inflate(R.layout.lv_home_item, null);
                TextView tv_original = (TextView) view.findViewById(R.id.tv_original);
                tv_original.setText(MyUtils.getdouble(item.getOriginalPrice()));
                tv_original.getPaint().setFlags(Paint.STRIKE_THRU_TEXT_FLAG);//添加下划线
                ImageView iv_item = (ImageView) view.findViewById(R.id.iv_item);
                Picasso.with(mContent).load(item.getUrl()).error(R.mipmap.ic_loadingerror).into(iv_item);
                TextView tv_price = (TextView) view.findViewById(R.id.tv_price);
                tv_price.setText(item.getPrice()+"");
//                tv_price.setText(MyUtils.getdouble(item.getPrice()));
                TextView tv_sales = (TextView) view.findViewById(R.id.tv_sales);
                tv_sales.setText("销量：" + item.getSales());
                TextView tv_title = (TextView) view.findViewById(R.id.tv_title);
                tv_title.setText(item.getName());
                TextView tv_giving = (TextView) view.findViewById(R.id.tv_giving);
                if (item.getCouponLimit() == 0) {
                    tv_giving.setText("");
                } else {
                    tv_giving.setText("最高抵扣" + (item.getCouponLimit() * 10) + "元");
                }
                TextView tv_merchantName = (TextView) view.findViewById(R.id.tv_merchantName);
                tv_merchantName.setText(item.getMerchantShortName());
                TextView tv_distance = (TextView) view.findViewById(R.id.tv_distance);
                intiDistance(tv_distance, item);
            }
            return view;
        }
    }

    /**
     * 距离计算
     *
     * @param
     * @param item
     */
    private void intiDistance(TextView tv, HostItem item) {
        LatLng startLatlng = new LatLng(StartActivity.mLatitude, StartActivity.mLongitude);
        LatLng endLatlng = new LatLng(Double.valueOf(item.getLatitude()), Double.valueOf(item.getLongitude()));

        double distance = AMapUtils.calculateLineDistance(startLatlng, endLatlng);
        distance = distance / 1000;
        DecimalFormat df = new DecimalFormat("0.##");
        String st = df.format(distance);
        tv.setText(st + "km");
    }


    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.iv_back:
                finish();
                break;
            case R.id.bt_item:
                iv_qcode.setDrawingCacheEnabled(true);
                iv_qcode.buildDrawingCache();
                bp = Bitmap.createBitmap(iv_qcode.getDrawingCache());
                wxShare();
                break;
        }
    }

    /**
     * 分享图片
     */
    private void wxShare() {
        WXImageObject wxImageObject = new WXImageObject(bp);
        WXMediaMessage msg = new WXMediaMessage();
        msg.mediaObject = wxImageObject;
        //设置缩略图
        Bitmap mBp = Bitmap.createScaledBitmap(bp, 120, 120, true);
        bp.recycle();
        msg.thumbData = bmpToByteArray(mBp, true);
        SendMessageToWX.Req req = new SendMessageToWX.Req();
        req.transaction = buildTransaction("img");//  transaction字段用
        req.message = msg;
        req.scene = SendMessageToWX.Req.WXSceneSession;
        BaseApp.msgApi.sendReq(req);
    }

    public static byte[] bmpToByteArray(final Bitmap bmp, final boolean needRecycle) {
        ByteArrayOutputStream output = new ByteArrayOutputStream();
        bmp.compress(Bitmap.CompressFormat.PNG, 100, output);
        if (needRecycle) {
            bmp.recycle();
        }

        byte[] result = output.toByteArray();
        try {
            output.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }

    private String buildTransaction(final String type) {
        return (type == null) ? String.valueOf(System.currentTimeMillis()) : type + System.currentTimeMillis();
    }
}
